package cn.bx.bid.service;


import cn.bx.bid.entity.*;
import cn.bx.bid.repository.ProfessorRepository;
import cn.bx.bid.repository.ProjectRepository;
import cn.bx.bid.repository.RandomNameRepository;
import cn.bx.bid.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//M V C
@Service
public class ProjectService {
    public static final int PAGE_SIZE = Page.PAGE_SIZE;

    @Autowired
    ProjectRepository projectRepository;

    @Autowired
    RandomNameRepository randomNameRepository;
    @Autowired
    ProfessorRepository professorRepository;

    //分页 paging
    public org.springframework.data.domain.Page<Project> paging(int pageNo, int pageSize, String projectName, String  projectCategory){
        Sort sort =Sort.by(Sort.Order.asc("id")); //排序

        PageRequest p=PageRequest.of(pageNo,pageSize,sort);
        return  projectRepository.findAll(new Specification<Project>(){
            @Override
            public Predicate toPredicate(Root<Project> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (projectName != null) {
                    predicateList.add((criteriaBuilder.like(root.get("projectName"), "%" + projectName + "%")));
                }
                if (projectCategory != null) {
                    predicateList.add((criteriaBuilder.like(root.get("projectCategory"), "%" + projectCategory + "%")));
                }
               criteriaQuery.where(predicateList.toArray(new Predicate[0]));
                return criteriaQuery.getRestriction();
            }

        },p);
    }

    //该项目详情 get
    public  Project get(long id){
      return   projectRepository.getOne(id);
    }

    // 删除项目 projectdel
    public int projectdel(long id){
        projectRepository.deleteById(id);
        return 1;
    }





    //批量删除  batchDeluserProject
    public int batchDeluserProject(@RequestParam("ids[]")long[] ids){
        LogUtil.info("ids>>>>>>>>>>>>>:"+ids);
        for(long id:ids){
            projectRepository.deleteById(id);
        }
        return ids.length;
    }

    //添加项目 projectadd
    public int projectadd(Project project){

        projectRepository.save(project);
        return 1;
    }

    //更新项目  projectupdate
    public int projectupdate(Project project){

       projectRepository.saveAndFlush(project);
        return 1;
    }


    public Page<ProfessorEnroll> searchProfessorInProjs(Long prjid) {
        List<RandomName> list1=randomNameRepository.findAllByProjectid(prjid);
        List<ProfessorEnroll> list=new ArrayList<>();
        ProfessorEnroll professorEnroll=new ProfessorEnroll();
        for(RandomName r:list1){
            professorEnroll.setProf(professorRepository.getOne(r.getProfessorid()));
            professorEnroll.setRand(r);
            list.add(professorEnroll);
        }
        return new Page<ProfessorEnroll>(list.size(), list);
    }

    public int getPrentProfessors(long id) {

        return randomNameRepository.getPrentProfessors(id);
    }

    //根据类型和查找专家，距离不能在这里做限制,同时排除掉已经选择的专家
    public List<Professor> getProfessorsForChoose(long prjid, String category) {
        List<RandomName> list1=randomNameRepository.findAllByProjectid(prjid);
        List<Professor> list=new ArrayList<>();
         for(RandomName r:list1){
           list.add(professorRepository.findAllByIdNotAndProjectCategory(r.getProfessorid(),category)) ;
         }
        return list;
    }

    //保存选择记录，并发短信
    public int saveChooseResult(Project p, long[] ids) {
        for (long id : ids) {
            RandomName r = new RandomName();
            r.setProjectid(p.getId());
            r.setProfessorid(id);
            r.setBePresent("不确定");

            r.setCreatedate(new Date());
            r.setIsNotice("是");
            r.setMsg("邀请您参加于" + p.getOpenDate() + " ，在" + p.getAddress() + "举行的" + p.getProjectName() + " 招标评标会议，请准时参加，不能参加请及时告知，联系人："+p.getLinkMan()+",电话"+p.getMobliePhone());
            r.setStatus("否");
            randomNameRepository.save(r);
            //Client.sendMsm("p.getMobilePhone",r.getMsg());
            return  1;
        }

        return ids.length;
    }
    //都加上判断是否要修改状态的判断
    //确定参加  profRoleProject

    /**
     * 确定能来
     * @param profid    专家号
     * @param projectid 项目号
     * @return
     */
    public int profRoleProject(long profid, long projectid) {
        int r = randomNameRepository.profRoleProject(profid, projectid);
        Project proj = projectRepository.getOne(projectid);
        //找到能来的人数
        int cancome = randomNameRepository.getComingProfessors(projectid);
        if (cancome >= proj.getProfessorNum()) {
            //人到齐了，修改项目状态为4，抽签完成
            projectRepository.updateProjectState(projectid, "4");
        } else {//补抽中
            projectRepository.updateProjectState(projectid, "3");
        }
        return r;
    }

    //不参加  profnotPresentProject

    public int profnotPresentProject(long pfid, long projectid, String reason) {

        int r = randomNameRepository.profnotPresentProject(pfid, projectid, reason);
        //记录专家未到次数
         Professor p= professorRepository.getOne(pfid);
        professorRepository.increaseNotPresentNum(pfid,p.getLostNum()+1);

        Project proj = projectRepository.getOne(projectid);
        //找到能来的人数
        int cancome = randomNameRepository.getComingProfessors(projectid);
        if (cancome >= proj.getProfessorNum()) {
            //人到齐了，修改项目状态为4，抽签完成
            projectRepository.updateProjectState(projectid, "4");
        } else {//补抽中
            projectRepository.updateProjectState(projectid, "3");
        }

        //
        return r;

    }

    //设置中标企业信息，并修改项目状态为5,
    public int settleProject(long projid, String dealCompany, double settlePrice) {

        int r=projectRepository.settleProject(projid,dealCompany,settlePrice);

        return r;

    }
}
